package com.slh.touchandroid.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;

public class ProgressDialogFragment extends DialogFragment {
	public static class Builder {
		private String title;
		private String message;
		private boolean cancelableOnTouchOutside = true;

		public ProgressDialogFragment.Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public ProgressDialogFragment.Builder setMessage(String message) {
			this.message = message;
			return this;
		}

		public ProgressDialogFragment.Builder setCancelableOnTouchOutside(
				boolean cancelable) {
			this.cancelableOnTouchOutside = cancelable;
			return this;
		}

		public ProgressDialogFragment build() {
			return ProgressDialogFragment.newInstance(title, message,
					cancelableOnTouchOutside);
		}
	}

	protected static ProgressDialogFragment newInstance() {
		return newInstance("", "", true);
	}

	protected static ProgressDialogFragment newInstance(String title,
			String message, boolean cancelableOnTouchOutside) {
		ProgressDialogFragment frag = new ProgressDialogFragment();
		Bundle args = new Bundle();
		args.putString("title", title);
		args.putString("message", message);
		args.putBoolean("cancelableOnTouchOutside", cancelableOnTouchOutside);
		frag.setArguments(args);
		return frag;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRetainInstance(true);
		super.onCreate(savedInstanceState);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		String title = getArguments().getString("title");
		String message = getArguments().getString("message");
		dialog.setCanceledOnTouchOutside(getArguments().getBoolean(
				"cancelableOnTouchOutside"));

		if (!TextUtils.isEmpty(title)) {
			dialog.setTitle(title);
		}

		if (!TextUtils.isEmpty(message)) {
			dialog.setMessage(message);
		}

		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setMax(100);
		return dialog;
	}

	public void setProgress(int progress) {
		((ProgressDialog) getDialog()).setProgress(progress);
	}

	@Override
	public void onDestroyView() {
		if (getRetainInstance() && getDialog() != null) {
			getDialog().setDismissMessage(null);
		}
		super.onDestroyView();
	}
}